<?php

namespace xingchen\adminApi\yii;

use xing\helper\yii\ReturnHelper;
use yii\data\ActiveDataProvider;

class YiiApiFormat extends \xingchen\adminApi\BaseApiFormat
{

    /**
     * @param ActiveDataProvider $dataProvider
     * @return array
     */
    public function formatSearchModel($dataProvider, $list = null)
    {
        $count = max(0, $dataProvider->getCount());
        if (($pagination = $dataProvider->getPagination()) !== false) {
            $totalCount = $dataProvider->getTotalCount();
            $begin = $pagination->getPage() * $pagination->pageSize + 1;
            $end = $begin + $count - 1;
            if ($begin > $end) {
                $begin = $end;
            }
            $page = $pagination->getPage() + 1;
            $pageCount = $pagination->pageCount;
        } else {
            $begin = $page = $pageCount = 1;
            $end = $totalCount = $count;
        }

//        $model = new $dataProvider->query->modelClass;
        $order = $dataProvider->query->orderBy ? $dataProvider->query->orderBy : $dataProvider->getSort()->getOrders();
        if (empty($list)) {
            $list = $dataProvider->query->offset($begin - 1)->limit($pagination->pageSize)->orderBy($order)->all();
        }
        return $this->returnList($this->formatList($list), [
            'begin' => $begin,
            'end' => $end,
            'count' => $count,
            'totalCount' => $totalCount,
            'page' => $page,
            'pageCount' => $pageCount,
            'pageSize' => $pagination->pageSize
        ]);
    }
}
